<template>
  <view class="withdraw-page">
    <!-- 自定义导航栏 -->
    <CustomNavBar title="提现" />
  
      <!-- 微信账户选择 -->
        <view class="account-section">
          <view class="account-item" @click="selectAccount">
            <text class="account-label">到{{ channel === 0 ? '支付宝' : '微信' }}账户</text>
            <view class="account-right">
              <uni-icons type="right" size="16" color="#999"></uni-icons>
            </view>
          </view>
        </view>
    
    <!-- 提现金额输入 -->
     <view class="amount-input-container">
        <view class="amount-section">
      <view class="amount-container">
        <text class="amount-label">提现金额</text>
        <view class="amount-input-wrapper">
          <text class="currency-symbol">¥</text>
          <input 
            class="amount-input" 
            type="digit" 
            placeholder="" 
            v-model="withdrawAmount"
            @input="onAmountInput"
          />
        </view>
        <view class="amount-underline"></view>
        <!-- 剩余可提现余额 -->
        <view class="balance-info">
          <text class="balance-text">剩余可提现余额：¥{{ currentBalance.toFixed(2) }}</text>
        </view>
      </view>
    </view>

     </view>
    
    
    <!-- 提现按钮 -->
    <view class="withdraw-button-container">
      <view 
        class="withdraw-button" 
        :class="{ disabled: !canWithdraw }"
        @click="handleWithdraw"
      >
        <text class="withdraw-text">提现</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import CustomNavBar from '@/components/CustomNavBar.vue'
import { withdraw, withdrawCancel, withdrawFirstNotify } from '@/api/app/withdraw.js'
import LoginUtils from '@/utils/loginUtils.js';

// 当前余额
const currentBalance = ref(0)

const channel = LoginUtils.getChannel();

// 提现金额
const withdrawAmount = ref(null)

// 是否可以提现
const canWithdraw = computed(() => {
  return withdrawAmount.value > 0 && (withdrawAmount.value <= currentBalance.value || withdrawAmount.value < 2000)
})

// 接收页面参数
onLoad((options) => {
  if (options.balance) {
    currentBalance.value = parseFloat(options.balance) || 0
  }
})

// 选择账户
const selectAccount = () => {
  // uni.showToast({
  //   title: '选择微信账户',
  //   icon: 'none'
  // })
}

// 金额输入处理
const onAmountInput = (e) => {
  let value = e.detail.value
  // 限制只能输入数字和小数点
  value = value.replace(/[^\d.]/g, '')
  // 限制只能有一个小数点
  const parts = value.split('.')
  if (parts.length > 2) {
    value = parts[0] + '.' + parts.slice(1).join('')
  }
  // 限制小数点后最多两位
  if (parts[1] && parts[1].length > 2) {
    value = parts[0] + '.' + parts[1].substring(0, 2)
  }
  // 转换为数字类型
  withdrawAmount.value = parseFloat(value) || 0
}

// 处理提现
const handleWithdraw = async () => {
  // 检查金额是否超过余额
  if (withdrawAmount.value > currentBalance.value) {
    uni.showToast({
      title: `当前可提现余额：¥${currentBalance.value.toFixed(2)}`,
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  if (!canWithdraw.value) {
    return
  }
  
   // 调用提现API
  let data = await withdraw({channel: channel,amount: withdrawAmount.value});
  if (channel === 0){
    transferSuccess();
  }else if (channel === 1){
    wxTransfer(data);
  }
}

const wxTransfer = (data) => {
  if (wx.canIUse('requestMerchantTransfer')) {
    wx.requestMerchantTransfer({
      mchId: data.mchId,
      appId: data.appId,
      package: data.packageStr,
      success: (res) => {
        // res.err_msg将在页面展示成功后返回应用时返回ok，并不代表付款成功
        console.log('success:', res);
      },
      fail: (res) => {
        withdrawCancel(data.id);
        console.log('fail:', res);
      },
      complete: (res) => {
        console.log('res:', res);
        if (res && res.errno === 4 && res.result === "cancel"){
          withdrawCancel(data.id);
        }
        if (res && res.errno === 0 && res.result === "success"){
          transferSuccess(data.id);
        }

      },
    });
  } else {
    withdrawCancel(data.id);
    wx.showModal({
      content: '你的微信版本过低，请更新至最新版本。',
      showCancel: false,
    });
  }
}

const transferSuccess = (id) => {
  uni.showToast({
    title: '提现成功',
    icon: 'success'
  });
  setTimeout(() => {
      uni.navigateTo({ url: '/pages/balance/balance' });
  }, 1000);
  if (id){
    withdrawFirstNotify(id);
  }
}

</script>

<style scoped>
.withdraw-page {
  min-height: 100vh;
  background-color: #fff;
}
/* 余额信息区域 */
.balance-info {
  margin-top: 20rpx;
}

.balance-text {
  font-size: 24rpx;
  color: #999;
  font-weight: 400;
}

/* 账户选择区域 */
.account-section {
  margin-top: 20rpx;
  background: linear-gradient(to bottom, #fff, #EFF2F6 );
  height:200rpx;
}

.account-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  /* border-bottom: 1rpx solid #f0f0f0; */
}

.account-label {
  font-size: 38rpx;
  color: #333;
  font-weight: 530;
}

.account-right {
  display: flex;
  align-items: center;
}

/* 提现金额区域 */
.amount-section {
  margin-top: 20rpx;
  background-color: #fff;
  /* padding: 150rpx 30rpx; */
  border: 1rpx solid #1CCCB4;
  border-radius: 17rpx;
  height:450rpx;
}

.amount-container {
  position: relative;
  padding: 36rpx 32rpx 0 32rpx;
}
.amount-input-container{
    position: absolute;
    padding:30rpx;
    top: 18%;
}
.amount-label {
  font-size: 34rpx;
  color: #333;
  margin-bottom: 40rpx;
  display: block;
  font-weight: 550;
}

.amount-input-wrapper {
  display: flex;
  align-items: baseline;
  margin-bottom: 20rpx;
  padding-top:100rpx;
}

.currency-symbol {
  font-size: 60rpx;
  color: #333;
  margin-right: 10rpx;
  line-height: 1;
}

.amount-input {
  flex: 1;
  font-size: 100rpx;
  height: 100rpx;
  color: #333;
  border: none;
  outline: none;
  background: transparent;
  padding: 0;
  line-height: 1;
}

.amount-input::placeholder {
  color: #ccc;
}

.amount-underline {
  height: 2rpx;
  background-color: #ddd;
  margin-top: 10rpx;
}

/* 提现按钮 */
.withdraw-button-container {
  position: fixed;
  bottom: 60rpx;
  left: 37rpx;
  right: 37rpx;
}

.withdraw-button {
  width: 100%;
  height: 95rpx;
  background: linear-gradient(135deg, #00D4AA 0%, #00B894 100%);
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 20rpx rgba(0, 212, 170, 0.3);
}

.withdraw-button.disabled {
  background: #ccc;
  box-shadow: none;
}

.withdraw-text {
  font-size: 36rpx;
  color: #fff;
  font-weight: 500;
}

.withdraw-button:active:not(.disabled) {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 10rpx rgba(0, 212, 170, 0.3);
}
</style>